package com.atguigu.schedule.util;

import com.atguigu.schedule.common.Result;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;

/**
 * @author yuezi2048
 * @version 1.0
 */
public class MyWebUtil {
    private static ObjectMapper objectMapper; // 封装为静态属性，静态代码块初始化

    static {
        objectMapper = new ObjectMapper();
    }

    /**
     * 用于向客户端响应JSON串的方法
     */
    public static void writeJson(HttpServletResponse resp, Result result){
        // 将result对象转换为JSON串响应给客户端（ObjectMapper）,已封装为一个工具方法
        resp.setContentType("application/json;charset=utf-8"); // 告诉客户端这是JSON串

        try {
            String info = objectMapper.writeValueAsString(result);
            resp.getWriter().write(info);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
